package com.warren.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.warren.common.constant.AuthServerConstant;
import com.warren.common.utils.HttpUtils;
import com.warren.common.utils.R;
import com.warren.common.vo.MemberRespVo;
import com.warren.gulimall.auth.feign.MemberFeignService;
import com.warren.gulimall.auth.vo.GiteeAccessToken;
import com.warren.gulimall.auth.vo.GiteeUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id","677d3c53e344c848e8ea55e7dacae90dc9cd2f72bd280beeb7c65cdc13fc0080");
        map.put("client_secret","21f1719d7eb080b51ba9fbfa1868f8cf5ee7a1eef4eabc40b193421cc039b772");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("grant_type","authorization_code");
        map.put("code",code);

        //根据code 换取access_token
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), new HashMap<>(), map);

        if (response.getStatusLine().getStatusCode() == 200){
            //获取到了giteeaccessToken
            String tokenJson = EntityUtils.toString(response.getEntity());
            GiteeAccessToken token = JSON.parseObject(tokenJson, GiteeAccessToken.class);
            //根据token 查询gitee open api 获取用户信息
            Map<String, String> query = new HashMap<>();
            query.put("access_token",token.getAccess_token());
            HttpResponse response_info = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), query);
            String giteeUserInfoJson = EntityUtils.toString(response_info.getEntity());
            GiteeUserInfo giteeUserInfo = JSON.parseObject(giteeUserInfoJson, GiteeUserInfo.class);
            //由于远程调用参数限制，这里我们把用户新塞进token暂存
            token.setGiteeUserInfo(giteeUserInfo);


            //登录或者注册这个社交用户
            //1.当前用户如果是第一次进入网站，就自动注册（为当前社交用户生成一个会员信息账号，以后这个社交账号就对应指定的会员
            R oauth2login = memberFeignService.oauth2Login(token);
            if (oauth2login.getCode() == 0){
                MemberRespVo data = oauth2login.getData(new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功,用户信息：{}", data.toString());
                //TODO 共享session问题 同一服务，复制多份，session不同步问题 不同服务，session不能共享问题
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                //登录成功返回首页
                return "redirect:http://gulimall.com";
            }else{
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
